package com.lzk.controller;

import com.lzk.domain.User;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Date;

@RestController
@RequestMapping("order")
@DefaultProperties(defaultFallback = "getByIdFallback")//统一降级 托底数据配置
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("getById/{id}")
    //开启接口的熔断功能，并指定降级方法托底数据
    //@HystrixCommand(fallbackMethod = "getByIdFallback")
    @HystrixCommand //在每个要熔断的服务上加，返回统一的熔断托底数据
    public User  getById(@PathVariable("id") Long id){
        //当前时间
        System.out.println(new Date().toLocaleString());
        //定义请求路径
        String url="http://user-server/user/getById/"+id;
        //使用restTemplate工具类发送http请求调用User接口
        User user = restTemplate.getForObject(url, User.class);
        //结束时间
        System.out.println(new Date().toLocaleString());
        return user;
    }

    //配置统一托底后，熔断方法无参数
    public User  getByIdFallback(){
        //该方法就是降级方法,参数和返回值要和被熔断的方法一致
        return new User(-1L,"hystrix","熔断托底数据！");
    }
}
